<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.num" placeholder="推广号" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">{{ $t('table.search') }}</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate" v-show='$store.state.user.roles[0]!="直营店" && $store.state.user.roles[0]!="加盟店"'>{{ $t('table.add') }}</el-button>
    </div>

    <el-table v-loading="listLoading" :key="tableKey" :data="list" border fit highlight-current-row style="width: 100%;">
      <el-table-column label="ID" prop="id" align="center" width="65" />
      <el-table-column label="企业名称" prop="companyName" align="center" />
      <el-table-column label="开始合作时间" prop="companyDate" align="center" />
      <el-table-column label="合作方联系人" prop="companyLinkman" align="center" />
      <el-table-column label="联系电话" prop="companyLinkPhone" align="center" />
      <el-table-column label="目前在职人数" prop="companyScale" align="center" />
      <el-table-column label="备注" prop="companyDesc" align="center" />
      <el-table-column label="是否回款" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.companyMoneyBack?'是': '否' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="success" @click="handleDetail(scope.row)">查看</el-button>
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)" v-show='$store.state.user.roles[0]!="直营店" && $store.state.user.roles[0]!="加盟店"'>编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)" v-show='$store.state.user.roles[0]!="直营店" && $store.state.user.roles[0]!="加盟店"'>删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="100px" style="width: 400px; margin-left:50px;">
        <el-form-item :label-width="formLabelWidth" label="公司名称">
          <!-- <el-input v-model="temp.companyName" placeholder="请输入内容"/> -->
          <el-select v-model="company" value-key="key" placeholder="请选择">
            <el-option v-for="item in enterpriseOptions" :key="item.key" :label="item.value" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="合作时间">
          <el-date-picker v-model="temp.companyDate" type="date" placeholder="选择日期" value-format="yyyy-MM-dd" />
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="合作联系人">
          <el-input v-model="temp.companyLinkman" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="合作联系人电话">
          <el-input v-model="temp.companyLinkPhone" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="公司规模">
          <el-input v-model="temp.companyScale" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="备注">
          <el-input v-model="temp.companyDesc" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="是否回款">
          <el-switch v-model="temp.companyMoneyBack" active-text="是" inactive-text="否" active-color="#13ce66" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
	fetchPolicyAjax,
	addPolicyAjax,
	updatePolicyAjax,
	delPolicyAjax
} from "@/api/finance";
import { fetchEnterPriseListAjax } from "@/api/enterprise";
import waves from "@/directive/waves"; // Waves directive
// import { parseTime } from "@/utils";
import Pagination from "@/components/Pagination"; // Secondary package based on el-pagination

// arr to obj ,such as { CN : "China", US : "USA" }
// const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
// 	acc[cur.key] = cur.display_name;
// 	return acc;
// }, {});

export default {
	name: "ComplexTable",
	components: { Pagination },
	directives: { waves },
	filters: {},

	data() {
		return {
			tableKey: 0,
			list: [],
			total: 0,
			tempTotal: 0,
			listLoading: true,
			listQuery: {
				pageNum: 1,
				pageSize: 10
			},
			tempListQuery: {
				pageNum: 1,
				pageSize: 10
			},
			textMap: {
				create: "新增政策",
				update: "更新政策"
			},
			downloadLoading: false,
			dialogFormVisible: false,
			temp: {},
			formLabelWidth: "150px",
			rules: {},
			dialogStatus: "",
			dialogDetailFormVisible: false,
			tempList: [],
			enterpriseOptions: [],
			company: null
		};
	},
	created() {
		this.getList();
		this.getEnterPriseOptions();
	},
	methods: {
		getEnterPriseOptions() {
			try {
				fetchEnterPriseListAjax().then(result => {
					console.log(result)
					result.data.data.forEach(item => {
						this.enterpriseOptions.push({
							key: item.id,
							value: item.companyName
						});
					});
				});
			} catch (err) {
				console.log(err);
			}
		},
		getList() {
			this.listLoading = true;
			this.listLoading = false;
			this.listLoading = true;
			fetchPolicyAjax(this.listQuery).then(response => {
				// if (respons.data.data.) {

				// }
				this.list = response.data.data.pageData;
				this.total = response.data.data.maxCount;
				this.listLoading = false;
			});
		},

		handleFilter() {
			this.listQuery.page = 1;
			this.getList();
		},

		handleCreate() {
			// this.resetTemp();
			this.temp = {};
			this.dialogStatus = "create";
			this.dialogFormVisible = true;
			this.$nextTick(() => {
				this.$refs["dataForm"].resetFields();
			});
		},

		createData() {
			this.$refs["dataForm"].validate(valid => {
				if (valid) {
					this.temp.company_id = this.company.key;
					this.temp.companyName = this.company.value;
					addPolicyAjax(this.temp).then(() => {
						this.dialogFormVisible = false;
						this.$notify({
							title: "成功",
							message: "创建成功",
							type: "success",
							duration: 2000
						});
						this.getList();
					});
				}
			});
		},
		handleUpdate(row) {
			this.company = {
				key: row.company_id,
				value: row.companyName
			}
			// this.company.key = row.company_id;
			// this.company.value = row.companyName;
			this.temp = Object.assign({}, row); // copy obj
			this.dialogStatus = "update";
			this.dialogFormVisible = true;
			this.$nextTick(() => {
				this.$refs["dataForm"].clearValidate();
			});
		},
		updateData() {
			this.$refs["dataForm"].validate(valid => {
				if (valid) {
					const tempData = Object.assign({}, this.temp);
					tempData.company_id = this.company.key;
					tempData.companyName = this.company.value;
					updatePolicyAjax(tempData).then(() => {
						// for (const v of this.list) {
						// 	if (v.id === this.temp.id) {
						// 		const index = this.list.indexOf(v);
						// 		this.list.splice(index, 1, this.temp);
						// 		break;
						// 	}
						// }
						this.dialogFormVisible = false;
						this.$notify({
							title: "成功",
							message: "更新成功",
							type: "success",
							duration: 2000
						});
						this.getList();
					});
				}
			});
		},
		handleDetail(data) {
			this.$router.push({
				name: "policyDetail",
				params: { id: data.id }
			});
		},
		handleDelete(row) {
			this.$confirm("确认删除该条数据吗?", "提示", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				type: "warning"
			}).then(() => {
				delPolicyAjax(row).then(res => {
					// const index = this.list.indexOf(row);
					// this.list.splice(index, 1);
					if (res.data.code !== 0 || res.data.data.length < 0) {
						this.$message({
							message: "删除失败",
							type: "error",
							duration: 5 * 1000
						});
						return;
					}
					this.$notify({
						title: "成功",
						message: "删除成功",
						type: "success",
						duration: 2000
					});
					this.getList();
				});
			});
		}
	}
};
</script>
